import { AlgengineApi } from '@/api/vmiot/algengine'
import { useMqttStore } from '@/store/modules/mqttStore'
import dayjs from 'dayjs'

export function useSignalView(widgetOptions, isPreview, mockDataUrl, resolveData, resolveMockData) {
  const refreshInterval = ref<any>()

  const chartStatus = ref<string>(isPreview && !widgetOptions.data.signal ? 'taskError' : '')

  const signal = computed(() => widgetOptions.data.signal)

  const mqtt = useMqttStore()

  // 销毁定时器
  const destroyInterval = () => {
    clearInterval(refreshInterval.value)
  }

  // 使用mqtt获取实时数据
  const startMqtt = () => {
    mqtt.subscribe(signal.value.signalAccessAddress, (payload) => {
      resolveData(JSON.parse(payload))
    })
  }

  // 使用http获取实时数据
  const getRealData = async () => {
    try {
      const data = await AlgengineApi.getSignalRealtime({
        signalAccessParams: signal.value.signalAccessParams
      })
      resolveData(data)
    } catch (e) {
      chartStatus.value = 'error'
    }
  }

  // 历史数据
  const getHistoryData = async () => {
    if (!signal.value) {
      return
    }
    const s = {
      signalName: signal.value.signalName,
      id: signal.value.signalId
    }

    const endTime = dayjs().valueOf() // 当前时间（毫秒）
    const startTime = dayjs().subtract(1, 'day').valueOf() // 前一天的当前时间（毫秒）

    try {
      const data = await AlgengineApi.getSignalHistory({
        signalAccessParams: JSON.stringify(s),
        dateRange: {
          startTime: startTime,
          endTime: endTime
        }
      })
      resolveData(data)
    } catch (e) {
      chartStatus.value = 'error'
    }
  }

  // mock 数据
  const getMockData = async () => {
    const jsonData = await fetch(mockDataUrl)
    const data = await jsonData.json()
    resolveMockData(data)
  }

  // 真实数据
  const getData = async () => {
    if (signal.value.signalAccessType.includes('HTTP')) {
      if (widgetOptions.data.isReal) {
        getRealData()
      } else {
        getHistoryData()
      }
      startInterval()
    } else {
      startMqtt()
    }
  }

  // 启动定时器
  const startInterval = () => {
    if (widgetOptions.data.refreshTime > 0) {
      refreshInterval.value = setInterval(() => {
        if (widgetOptions.data.isReal) {
          getRealData()
        } else {
          getHistoryData()
        }
      }, widgetOptions.data.refreshTime)
    }
  }

  // 刷新数据
  const refreshData = () => {
    if (isPreview) {
      getData()
    } else {
      getMockData()
    }
  }

  onBeforeUnmount(() => {
    destroyInterval()
  })

  return {
    chartStatus,
    refreshData
  }
}
